import { getUserInfo, loginByPhone, loginByWxPhone } from '@/api/user'
import { getToken, removeStorageCache, setToken } from '@/common/cache'
import { AuthTypeEnum } from '@/common/enums/userEnum'
// 设置默认State
const getDefaultState = () => {
  return {
    token: getToken() || '',
    isLogin: !!getToken(), // 是否登陆
    userInfo: {}, // 用户信息
    roles: [],
  }
}
// 初始化State
const state = getDefaultState()

const mutations = {
  SET_TOKEN(state, token) {
    state.token = token
    state.isLogin = token ? true : false
    setToken(token)
  },

  // 用户信息
  SET_USER_INFO(state, data) {
    state.userInfo = data
    // setStorageCache('userInfo', data)
  },

  RESET_STATE(state) {
    Object.assign(state, getDefaultState())
  },
}

const actions = {
  ResetState({ commit }) {
    commit('RESET_STATE')
  },

  // 登录
  async Login({ commit, dispatch }, params) {
    return new Promise(async (resolve, reject) => {
      const { type } = params
      let result = null
      switch (type) {
        case AuthTypeEnum.MOBILE.type:
          result = await loginByPhone(params)
          break

        case AuthTypeEnum.WXMOBILE.type:
          result = await loginByWxPhone(params)
          break
      }

      if (result.errcode === 0) {
        commit('SET_TOKEN', result?.data?.token || '')
        try {
          const res = await dispatch('GetUserInfo')
          resolve(res)
        } catch (error) {
          reject(error)
        }
      } else {
        reject(result)
      }
    })
  },

  // 获取用户信息
  async GetUserInfo({ commit, dispatch, getters, state }) {
    return new Promise(async (resolve, reject) => {
      const result = await getUserInfo()
      if (result.errcode === 0) {
        commit('SET_USER_INFO', result.data || {})
        resolve(result)
      } else {
        reject(result)
      }
    })
  },

  async addShareLog() {},

  // 退出登录
  async Logout({ commit, dispatch }) {
    commit('SET_TOKEN', '')
    commit('SET_USER_INFO', {})
    removeStorageCache('history')
    removeStorageCache('reservedCompany')
    // 重置store
    dispatch('ResetState') // 用户模块
    dispatch('app/ResetState', null, { root: true }) // app模块
    dispatch('modal/ResetState', null, { root: true }) // modal模块
    dispatch('system/ResetState', null, { root: true }) // system模块
    // dispatch('location/ResetState', null, { root: true }) // location模块
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
